from fastapi import APIRouter, HTTPException, Depends
from backend.models.user_model import UserLogin, UserRegister
from backend.utils.security import get_password_hash, verify_password, create_access_token
from backend.utils.database import get_user_by_username, create_user

router = APIRouter()

# 登录
@router.post("/login")
async def login(user: UserLogin):
    db_user = get_user_by_username(user.username)
    if not db_user or not verify_password(user.password, db_user["password"]):
        raise HTTPException(status_code=401, detail="用户名或密码错误")

    access_token = create_access_token(
        data={"sub": db_user["username"],"user_id": db_user["id"],"role": db_user["role"]})
    return {"message": "登录成功",
            "access_token": access_token,
            "token_type": "bearer",
            "username": db_user["username"],
            "role": db_user["role"]}
# 注册,默认角色为普通用户
@router.post("/register")
async def register(user: UserRegister):
    # 检查用户名是否已存在
    if get_user_by_username(user.username):
        raise HTTPException(status_code=400, detail="用户名已存在")

    # 创建用户（密码哈希处理）
    password_hash = get_password_hash(user.password)
    user_id = create_user(user.username, password_hash, user.email, user.role)

    return {"message": "注册成功", "user_id": user_id, "role": user.role}